/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.cicp.message;

import java.io.Serializable;
import java.lang.reflect.Method;

import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.ProbeEnv;
import com.sinodata.bsm.cicp.service.ServiceFactory;
import com.sinodata.bsm.common.message.BsmActiveMQFactory;
import com.sinodata.bsm.common.message.ServiceMessage;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author tangli
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-5-14 下午3:35:22          tangli         1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class SyncMessageListener implements MessageListener, ExceptionListener {
    private static final Logger logger = Logger.getLogger(SyncMessageListener.class);
    private static SyncMessageListener instance = new SyncMessageListener();
    private Session session;
    private Destination destination;
    private String queueName = null;
    private MessageConsumer consumer = null;
    private int ackMode = Session.AUTO_ACKNOWLEDGE;
    private boolean isRunning = false;

    private SyncMessageListener() {
        try {
            queueName = "SYNC_CTP_" + ProbeEnv.probeId;
            session = BsmActiveMQFactory.getInstance().getSession(false, ackMode);
            destination = session.createQueue(queueName);
            consumer = session.createConsumer(destination);
            clean(consumer);
            consumer.setMessageListener(this);
        } catch (Exception ex) {
            logger.error("error create message queue:" + this.queueName, ex);
        }
    }

    public static SyncMessageListener getInstance() {
        return instance;
    }

    public void start() {
        this.isRunning = true;
    }

    public void stop() {
        this.isRunning = false;
    }

    /**
     * 注意，此队列是同步对列，注动接收消息，方法没有执行完之后，将不会异步执行后面发过来的请求消息
     */
    public void onMessage(Message message) {
        logger.debug("recive sync message:" + message);
        if (!isRunning) {
            return;
        }
        new MyThread(message).start();
    }

    private void clean(MessageConsumer consumer) {
        while (true) {
            try {
                Message msg = consumer.receive(1000L);
                if (msg == null) {
                    logger.info("队列中没有消息");
                    break;
                }
                //                else{
                //                    logger.info("删除消息："+msg);
                //                    try {
                //                        MessageProducer replyProducer;
                //                        replyProducer = session.createProducer(null);
                //                        replyProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
                //                        replyProducer.send(msg.getJMSReplyTo(), session.createObjectMessage("消息已过期"));
                //                    } catch (Exception e) {
                //                        logger.fatal("回复中心会话失败", e);
                //                    }
                //                    
                //                }
            } catch (JMSException e) {
                logger.error("清空消息队列失败", e);
                break;
            }
        }
    }

    public synchronized void onException(JMSException ex) {
        logger.error("", ex);
    }

    class MyThread extends Thread {
        private Message message;

        public MyThread(Message message) {
            this.message = message;
        }

        public void run() {
            Serializable response = null;
            try {
                ObjectMessage objmsg = (ObjectMessage) message;
                Object msg = objmsg.getObject(); //待序列化的消息
                if (msg instanceof ServiceMessage) {
                    ServiceMessage serviceMessage = (ServiceMessage) msg;
                    String serviceId = serviceMessage.getSrvId();
                    String methodName = serviceMessage.getMethod();
                    Object[] params = serviceMessage.getParams();
                    boolean isNeedReply = serviceMessage.isNeedReply();
                    Object service = ServiceFactory.get(serviceId);
                    Class[] paramTypes = null;
                    if (params != null) {
                        paramTypes = new Class[params.length];
                        for (int i = 0; i < paramTypes.length; i++) {
                            paramTypes[i] = params[i].getClass();
                        }
                    }
                    logger.debug("begin invoke serivce=" + serviceId + ";method=" + methodName);
                    Method method;
                    method = service.getClass().getDeclaredMethod(methodName, paramTypes);
                    response = (Serializable) method.invoke(service, params);
                }
            } catch (Exception e) {
                logger.error("failed to get method", e);
            } finally {
                try {
                    MessageProducer replyProducer;
                    replyProducer = session.createProducer(null);
                    replyProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
                    replyProducer.send(message.getJMSReplyTo(), session.createObjectMessage(response));
                } catch (Exception e) {
                    logger.fatal("回复中心会话失败", e);
                }
            }
        }
    }
}
